//
//  ZDBFeedbackViewController.m
//  ZDB
//
//  Created by Kk on 2020/3/27.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBFeedbackViewController.h"
#import "CustomViewController.h"
#import "BottomCustomAlert.h"
#import "ZDBFeedbackListViC.h"
#import "UITextView+YLTextView.h"
#import "ZDBFeedbackCollectionViewCell.h"
#import "HUPhotoBrowser.h"
@interface ZDBFeedbackViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,TZImagePickerControllerDelegate>
@property (nonatomic,assign)NSInteger type;
@property (nonatomic,strong)NSMutableArray * images;
@property(strong,nonatomic)NSString * kUploadIconImageToken;
@property(nonatomic,strong)NSMutableArray * imagkeys;//上传成功之后的key
@end

@implementation ZDBFeedbackViewController
- (void)viewWillAppear:(BOOL)animated
{
     [self SetnavigationBarBackgroundImage:VIEWBGCOLOR Alpha:1];
}
- (void)viewWillDisappear:(BOOL)animated
{
     [self SetnavigationBarBackgroundImage:WHITECOLOR Alpha:1];
}
- (void)axcBaseClickBaseRightImageBtn:(UIButton *)sender
{
    [self.navigationController pushViewController:[ZDBFeedbackListViC new] animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _type =1;
    [self axcBaseClickBaseRightTitleStr:@"我的反馈"];
    WeakSelf
    [self.feedBackBtn add_BtnClickHandler:^(NSInteger tag) {
        [weakSelf getFeedbackType];
    }];
    [self.subimtBtn add_BtnClickHandler:^(NSInteger tag) {
        [weakSelf subimetRequest];
    }];
    [self initTextView];
    [self initCollectionView];
    KViewRadius(_subimtBtn, _subimtBtn.height/2);
    [self getAvatarQiniuToken];
}
- (void)initTextView
{
     _textView.limitLength=@200;
     _textView.placeholder = @"输入反馈内容";
     [_contenView addSubview:_textView.wordCountLabel];
}
- (void)initCollectionView
{
    _collectionView.delegate =self;
    _collectionView.dataSource= self;
    [_collectionView registerClass:[ZDBFeedbackCollectionViewCell class] forCellWithReuseIdentifier:@"ZDBFeedbackCollectionViewCell"];
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
}
- (NSMutableArray *)images
{
    if (!_images) {
        _images = [NSMutableArray new];
    }
    return _images;
}
#pragma 反馈类型 1=软件BUG 2=改进建议 3=数据错误 4=其他问题
- (void)getFeedbackType
{
    WeakSelf
    NSArray * showDatas=@[@"APP问题",@"改进建议",@"数据错误",@"其他问题"];
    CustomViewController * custom = [[CustomViewController alloc] initWithCustomContentViewClass:@"BottomCustomAlert" delegate:self];
    custom.direction = FromBottom;
    [custom show:showDatas];
    
    BottomCustomAlert *aleatView = (BottomCustomAlert *)custom.contentView;
    aleatView.index = weakSelf.type-1;
    aleatView.cancelBlock = ^{
        [custom dismiss];
    };
    aleatView.selectIndexPathRow = ^(NSInteger index) {
        [weakSelf.feedBackBtn setTitle:showDatas[index] forState:0];
        weakSelf.type = index+1;
        [custom dismiss];
    };
}
#pragma 提交数据
- (void)subimetRequest
{
    if (kStringIsEmpty(_titleField.text)) {
       [JMNotifyView showNotify:@"请填写反馈标题" isSuccessful:NO];;
        return;
    }
    if ([ZBDUnit JudgeTheillegalCharacter:_titleField.text])
    {
        [JMNotifyView showNotify:@"标题不能包含特殊字符" isSuccessful:NO];
        return;
    }
    if (kStringIsEmpty(_textView.text)) {
       [JMNotifyView showNotify:@"请填写反馈内容" isSuccessful:NO];;
        return;
    }
     self.subimtBtn.userInteractionEnabled = NO;
    if (_images.count>0) //上传图片
    {
        if (self.kUploadIconImageToken)
           {
             [self showLoadingAnimation];
             self.imagkeys = [NSMutableArray new];
             QNUploadManager *upManager = [[QNUploadManager alloc] init];
             [self uploadImages:self.images atIndex:0 token:self.kUploadIconImageToken uploadManager:upManager keys:self.imagkeys];
               
           }else
           {
               [self getAvatarQiniuToken];
           }
         
    }else
    {
         [self showLoadingAnimation];
         [self uploadfeedbackInfo:nil];
    }
}
-(void)uploadImages:(NSArray *)images atIndex:(NSInteger)index token:(NSString *)token uploadManager:(QNUploadManager *)uploadManager keys:(NSMutableArray *)keys;{
    UIImage *image = images[index];
    __block NSInteger imageIndex = index;
    NSData *data = UIImageJPEGRepresentation(image, 0.8);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    WeakSelf
    NSString *key = [NSString stringWithFormat:@"iOS%@.jpg", [formatter stringFromDate:[NSDate date]]];
    [uploadManager putData:data key:key token:token
                  complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                      if (info.isOK) {
                          [keys addObject:key];
                          imageIndex++;
                          if (imageIndex >= images.count) {
                              NSLog(@"上传完成");
                              [weakSelf uploadfeedbackInfo:keys];
                              return ;
                          }
                          [self uploadImages:images atIndex:imageIndex token:token uploadManager:uploadManager keys:keys];
                      }else
                      {
                          [self stopLoadingAnimation];
                          weakSelf.subimtBtn.userInteractionEnabled = YES;
                           [JMNotifyView showNotify:@"上传照片失败" isSuccessful:NO];
                      }
         
    } option:nil];
}
#pragma 上传反馈信息
- (void)uploadfeedbackInfo:(NSMutableArray *)imagekeys
{
    NSLog(@"====>%@",imagekeys);
    NSMutableString * keymustr = [[NSMutableString alloc] init];;
   ;
    if (!kArrayIsEmpty(imagekeys)) {
        for (NSString * imageFile in imagekeys)
        {
            [keymustr appendString:kFormat(@"%@,",imageFile)];
        }
        NSRange deleteRange = {[keymustr length] - 1, 1 };
        [keymustr deleteCharactersInRange:deleteRange];
    }
    NSMutableDictionary * diccc = [NSMutableDictionary dictionary];
    [diccc setValue:_textView.text forKey:@"content"];
    [diccc setValue:kStringIsEmpty(keymustr)?@"":keymustr forKey:@"images"];
    [diccc setValue:_titleField.text forKey:@"title"];
    [diccc setValue:@(_type) forKey:@"type"];
    
    WeakSelf
    NSString  * addFeedback = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"addFeedback"];
    [[SmileHttpTool sharedInstance] POST:addFeedback parameters:diccc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
        if (statusCode ==0)  {
            [JMNotifyView showNotify:@"反馈信息已提交" isSuccessful:NO];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }else
        {
            [JMNotifyView showNotify:message isSuccessful:NO];;
        }
        weakSelf.subimtBtn.userInteractionEnabled = YES;
        [self stopLoadingAnimation];
        
    } failure:^(id responseObject, NSError *error) {
        weakSelf.subimtBtn.userInteractionEnabled = YES;
        [self stopLoadingAnimation];
    }];
}
//获取七牛头像token
-(void)getAvatarQiniuToken{
    [self showLoadingAnimation];
    WEAKSELF
    [[SmileHttpTool sharedInstance] getTokenFromQiNiu:@"" resultBlock:^(BOOL isSuccess, NSString *token) {
        [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf)
        if (isSuccess) {
            strongSelf.kUploadIconImageToken = token;
           
        }
    }];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.images.count >=4)
    {
        return self.images.count;
    }
    return  self.images.count+1;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    ZDBFeedbackCollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.row inSection:0]];
    if (self.images.count >=4) {//查看图片浏览器
        
         [HUPhotoBrowser showFromImageView:cell.icon withImages:_images atIndex:indexPath.row];
    }else
    {
        if (indexPath.row == _images.count) {//添加
            
            [self uploadImage];
            
        }else //查看图片浏览器
        {
             [HUPhotoBrowser showFromImageView:cell.icon withImages:_images atIndex:0];
        }
    }
    
   
   
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    return CGSizeMake(50, 50);
 
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZDBFeedbackCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZDBFeedbackCollectionViewCell" forIndexPath:indexPath];
    if (self.images.count >=4)
    {
        item.icon.image =  _images[indexPath.row];;
       
        item.deleteBtn.hidden = NO;
    }else
    {
        if (indexPath.row == _images.count) {
            item.icon.image = [UIImage imageNamed:@"add_alipay"];
            item.deleteBtn.hidden = YES;
        }else
        {
            item.icon.image = _images[indexPath.row];
            item.deleteBtn.hidden = NO;
        }
    }
    WeakSelf
    [item.deleteBtn add_BtnClickHandler:^(NSInteger tag) {
        
        [weakSelf.images removeObjectAtIndex:indexPath.row];
        [weakSelf.collectionView reloadData];
    }];
    return item;
    
}
- (void)uploadImage {

    WeakSelf
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:4 - weakSelf.images.count  delegate:self];
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowPickingGif = NO;
    if (@available(iOS 13.0, *)) {
        imagePickerVc.statusBarStyle = UIStatusBarStyleDarkContent;
    } else {
        imagePickerVc.statusBarStyle = UIStatusBarStyleDefault;
      
    }
    imagePickerVc.alwaysEnableDoneBtn = YES;
    imagePickerVc.allowPickingVideo = NO; //不许选择视频
    imagePickerVc.allowPickingMultipleVideo = NO;//不允许选择视频gif
    imagePickerVc.barItemTextColor = [UIColor colorWithHexString:@"#333333"];
    imagePickerVc.naviTitleColor = [UIColor colorWithHexString:@"#333333"];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        for (UIImage * image in photos)
        {
            [weakSelf.images addObject:image];
        }
        [weakSelf.collectionView reloadData];
     
    }];
    imagePickerVc.modalPresentationStyle = 0;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}
@end
